<template>
  <div class="user-login-layout  home-main-box">
    <el-dialog title="尊敬的用户：" :visible.sync="dialogVisible " :append-to-body="true" :close-on-click-modal="false" width="400px" @closed="close">
        <p style="line-height:25px;margin-left:15px;">你好，3YData智能投放平台近期将进行数据整合和策</p>
          <p style="line-height:25px;">略更改，将暂时关闭自主投放功能。如您有广告投放需求，欢迎联系我们。</p>
        <img :src="img" style="height: 150px; width: 150px;margin-left:100px;margin-top:15px;"/>
        <p style="text-align:center;margin-top:15px;">扫码联系我们</p>
    </el-dialog>
    <div class="user-login-form form">
      <el-form ref="loginForm" :model="form" :rules="rules" size="medium">

        <el-form-item prop="user" style="width: 100%;">
          <el-input v-model.trim="form.user" type="text" placeholder="请输入您的电话/邮箱" class="user-pwd-input">
            <svg-icon slot="prefix" icon-class="user" />
          </el-input>
        </el-form-item>

        <el-form-item prop="pwd">

          <pwdInput v-model.trim="form.pwd" show-password placeholder="请输入您的密码" class="user-pwd-input" @keyup.enter.native="submitLogin">
            <svg-icon icon-class="pwd" />
          </pwdInput>
        </el-form-item>
        <div v-if="false" class="code-box">
          <el-form-item prop="code">
            <el-input v-model.trim="form.code" placeholder="获取验证码" @keyup.native.enter="submitLogin" />
          </el-form-item>
          <img v-if="code" :src="code" class="code-img" @click="createCode">

          <el-button v-else class="msg-btn blue-btn" size="small" type="primary" @click="createCode">点击获取</el-button>

        </div>

        <div class="login-list">
          <div class="pwd-box flex">
            <el-checkbox v-model.trim="checked" text-color="#24BEBE"><span style="font-size: 14px;">记住密码</span></el-checkbox>
            <span class="find-pwd" style="cursor: pointer;font-size: 14px;padding: 0;" @click="handleChangeType('findPwd')">忘记密码</span>
          </div>

          <el-form-item>
            <div class="btn-list">
              <el-button
                v-loading="loginLoading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                type="success"
                size="small"
                class="login-btn"
                @click="submitLogin"
              >登录</el-button>
            </div>
          </el-form-item>

        </div>
      </el-form>

    </div>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import {
  asyncRoutes
} from '@/router'
import {
  userCode,
  createCode,
  login,
  findCampaignCount,
  getInfo
} from '@/api/user.js'
import {
  isValidUsername
} from '@/utils/validate'
import {
  mapActions
} from 'vuex'
import { resetRouter } from '@/router'
import {
  getDefultPath
} from '@/utils/index.js'
export default {
  data() {
    const isValidCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.length < 4) {
        callback(new Error('验证码格式错误'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      img: require("@/assets/images/homepage/code3.png"),
      loginLoading: false,
      checked: true,
      code: undefined, // 验证码图片路径
      form: {
        user: '',
        // user: '15360089159',
        pwd: '',
        // pwd: '12345678a',
        code: ''
      },
      rules: {
        user: [{
          required: true,
          message: '请输入电话/邮箱',
          trigger: 'blur'
        },
        {
          validator: isValidUsername,
          trigger: 'blur'
        }
        ],
        pwd: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        code: [{
          validator: isValidCode,
          trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
    // this.createCode()
    const obj = Cookies.get('3Y_DATA_LOGIN_INFO') ? JSON.parse(JSON.stringify(Cookies.get('3Y_DATA_LOGIN_INFO')))
      : undefined
    if (obj) {
      const data = JSON.parse(obj)
      this.form.user = data.email || data.mobile
      this.form.pwd = data.pwd||''
    }
  },
  methods: {
    close() {
      this.$router.push('/home')
    },
    // ...mapActions([
    //         // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    //       'user.login',

    //     ]),
    // 获取验证码
    async createCode() {
      const res = await createCode()
      const blob = new Blob([res.data], {
        type: 'image/png'
      })
      const url = window.URL.createObjectURL(blob)
      this.code = url
    },
    // 清除表单数据
    resetForm() {
      this.$refs['loginForm'].resetFields()
    },

    // 去注册页面
    // goRegister() {

    //   this.$emit('typeChange', 'register')
    // },
    // 切换显示类型
    handleChangeType(type) {
      this.resetForm()
      this.$emit('changeType', type)
    },
    // 提交登录
    submitLogin() {
      const windowWidth = document.body.clientWidth
      if (windowWidth < 900) {
        this.$message.closeAll()
        this.$message.error('请在PC端登录')
        return false
      }
      // this.dialogVisible = true
      this.$refs['loginForm'].validate(async(valid) => {
        if (valid) {
          // alert('submit!');
          // const res = await this.codeIsTrue()
          // if (res) {
          this.userLogin()
          // }
        } else {
          return false
        }
      })
    },

    // 验证图片验证码是否正确
    async codeIsTrue() {
      if (this.form.code.length < 4) {
        this.$message.closeAll()
        return false
      } else {
        const {
          data
        } = await userCode(this.form.code)
        if (data.code !== 20000) {
          this.$message.closeAll()
          this.$message.error(data.message || '验证码错误')
          this.createCode()
          return false
        } else {
          return true
        }
      }
    },
    // 用户名登录的方法
    async userLogin() {
      /* console.log('进入这里了吗') */
      this.loginLoading = true
      let formlist = {}
      // 判断是邮箱登录还是手机号码登录
      if (this.form.user.indexOf('@') !== -1) {
        formlist = {
          email: this.form.user,
          pwd:this.form.pwd
        }
      } else {
        formlist = {
          mobile: this.form.user,
          pwd:this.form.pwd
        }
      }
      /* console.log('登录信息', formlist) */
      try {
        const res = await this.$store.dispatch('user/login', formlist)
        // console.log(res, '你好')
        const {
          data
        } = res

        if (data.code === 20000) {
          if (this.checked) {
            // 存储登录信息
            Cookies.set('3Y_DATA_LOGIN_INFO', JSON.stringify(formlist), {
              'expires': 7
            })
          }
          // 验证是不是首次登录
          const userInfo = await this.$store.dispatch('user/getInfo')
          const path = getDefultPath(userInfo.roleName)
          this.$router.replace({
            path
          })
        } else {
          this.loginLoading = false
          this.$message.closeAll()
          this.$message.error(data.message || '登录失败，请稍后重试')
          // this.createCode()
        }
      } catch (error) {
        this.loginLoading = false
        console.log(error)
        // this.createCode()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  @import './style/form.scss';

  .login-list {

    ::v-deep.el-checkbox__input.is-checked+.el-checkbox__label,
    span.find-pwd {
      color: #24BEBE !important;
      margin-top: -2px;

    }

    span.find-pwd {
      margin-left: 24px;
    }
  }
</style>
